package com.mobapping;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.mobapping.IDataAdapter.ElementInfo;
import com.mobapping.IDataAdapter.IArrayListDataListener;

public class Main extends Activity {
	private static final String ACTION_SHOW_PHARMACIES = "com.listview.showPharmacies";
	private static final String ACTION_START_MAP = "com.listview.startmap";
	private static final String ACTION_SEARCH_PHARMACIES = "com.listview.searchPharmacies";
	private static final String CITY_KEY = "City";
	private static final String CITY_LATITUDE = "City_latitude";
	private static final String PHARMACY_URL = "Pharmacy_url";
	private static final String CITY_LONGITUDE = "City_longitude";
	private static final String  SEARCH_KEYWORD= "Search";
	private static final String ACTION_SHOW_PHARMACY_ONMAP ="com.listview.showPharmacyonMap";
	private static final String PHARMACY_NAME = "com.listview.PharmacyonName";
	private static final String PHARMACY_ADDRESS = "com.listview.PharmacyonAdress";
	private static final String PHARMACY_PHONE = "com.listview.PharmacyonPhone";
	private ElementInfo[] pharmacies;
	private EditText edittext;

	private ProgressDialog pDialog,pDialog2;
	int city_id;
	String search_keyword;
	private ListView listView;
	/** Called when the activity is first created. */
	@Override

	public void onCreate(Bundle savedInstanceState) {


		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		super.onCreate(savedInstanceState);    
		setContentView(R.layout.main);

		String action = getIntent().getAction();      
		Intent i = getIntent();

		final ImageButton searchButton = (ImageButton) findViewById(R.id.imageButton1);
		edittext = (EditText) findViewById(R.id.editText1);
		listView = (ListView) findViewById(R.id.listView1);
		city_id=i.getIntExtra(CITY_KEY, 0); 
		search_keyword=i.getStringExtra(SEARCH_KEYWORD);
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();

		AlertDialog.Builder ad = new AlertDialog.Builder(this);  
		//ad.setTitle("MobApping");  
		ad.setMessage(R.string.Internet_uyari);   
		ad.setPositiveButton(R.string.tamam, new DialogInterface.OnClickListener() {  
			public void onClick(DialogInterface dialog, int id) {  
				dialog.cancel();
				finish(); 
			}  
		});  
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {
		
				pDialog = ProgressDialog.show(Main.this, "",getString(R.string.datayukleniyor), true, true);    	  
				IDataAdapter adapter = new WebAdapter();

				if(action.equals(ACTION_SEARCH_PHARMACIES) == true)
				{
					edittext.setText(search_keyword);
					
					adapter.search(search_keyword,city_id, new IArrayListDataListener() { 

						public void dataArrived(ArrayList<Object> data) {
							if(data != null)
							{
								int size = data.size();
								if(size>0){
									pharmacies = new ElementInfo[size];
									for (int i = 0; i < size; i++) {
										pharmacies[i]= (ElementInfo)data.get(i); 
									}
									listView.setAdapter(new PharmacyAdapter(getApplicationContext(), pharmacies));
									listView.setBackgroundResource(R.drawable.customshape);
									

								}
								else
								{
									finish();
									Toast.makeText(getApplicationContext(), getString(R.string.data_bulunamadi), Toast.LENGTH_SHORT).show();
								}
									
							}
							else
							{
								finish();
								Toast.makeText(getApplicationContext(), getString(R.string.data_bulunamadi), Toast.LENGTH_SHORT).show();
							}
							pDialog.cancel();
						}
					});

				}
				else
				{
					adapter.getElements(city_id, new IArrayListDataListener() {
						public void dataArrived(ArrayList<Object> data) {
							if(data != null){
								int size = data.size();
							
								if(size>0){
									pharmacies = new ElementInfo[size];
									for (int i = 0; i < size; i++) {
										pharmacies[i]= (ElementInfo)data.get(i); 
									}
									listView.setAdapter(new PharmacyAdapter(getApplicationContext(), pharmacies));
									listView.setBackgroundResource(R.drawable.customshape);
								}
								
							}
							pDialog.cancel();
						}
					}); 
				}
				// listView.setOnItemClickListener(new OnItemClickListener() {
			listView.setOnItemLongClickListener(new OnItemLongClickListener() {

				@Override

				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {
					ElementInfo pharmacy =(ElementInfo)(listView.getAdapter().getItem(position));
					
				
					if (pharmacy.phoneNumber != null ){
						Intent callIntent = new Intent(Intent.ACTION_DIAL);
						callIntent.setData(Uri.parse("tel:"+(String)pharmacy.phoneNumber));
						startActivity(callIntent);
					}
					else if (pharmacy.lattitude != 0) // ankaradir uyumlu servisler
					{
						
						Intent i = new Intent(Main.this, Harita.class);
						i.putExtra(CITY_LATITUDE, pharmacy.lattitude);
						i.putExtra(CITY_LONGITUDE, pharmacy.longitude);
						i.setAction(ACTION_START_MAP);
						startActivity(i);   
					}
					else {
					
					}
					
					

					//Toast.makeText(Main.this, "Alperen adami hasta etme", Toast.LENGTH_LONG).show();// TODO Auto-generated method stub
					return true;
				}
			});

			listView.setOnItemClickListener(new OnItemClickListener() {


				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

					ElementInfo pharmacy =(ElementInfo)(listView.getAdapter().getItem(position));

/*					if (pharmacy.id == 1) // ankaradir uyumlu servisler
					{
						Intent i = new Intent(Main.this, Harita.class);
						i.putExtra(CITY_LATITUDE, pharmacy.lattitude);
						i.putExtra(CITY_LONGITUDE, pharmacy.longitude);
						i.setAction(ACTION_START_MAP);
						startActivity(i);   
					}
					else {*/
						if(pharmacy.isPharmacy == false)
						{
							// Toast.makeText(getApplicationContext(), String.valueOf(id), Toast.LENGTH_SHORT).show();        	
							Intent i = new Intent(Main.this, Main.class);
							i.setAction(ACTION_SHOW_PHARMACIES);
							i.putExtra(CITY_KEY, (int)id);            
							startActivity(i); 	
						}
						else if(pharmacy.lattitude!=0){

							Intent i = new Intent(Main.this, Harita.class);
							i.putExtra(CITY_LATITUDE, pharmacy.lattitude);
							i.putExtra(CITY_LONGITUDE, pharmacy.longitude);
							i.putExtra(PHARMACY_NAME, pharmacy.name);  
							i.putExtra(PHARMACY_ADDRESS, pharmacy.address);  
							i.putExtra(PHARMACY_PHONE, pharmacy.phoneNumber);  
							i.setAction(ACTION_SHOW_PHARMACY_ONMAP);
							startActivity(i);   

						}
						else if (!(pharmacy.URL == null || pharmacy.URL.equals("0") == true))//(pharmacy.URL != null)
						
							{
								
							Intent i = new Intent(Main.this, Web_View.class);
							i.putExtra(PHARMACY_URL, pharmacy.URL);								
								startActivity(i);   
							}
				//	}


				}

			});


			searchButton.setOnClickListener(new OnClickListener() { 


				public void onClick(View v) {  


					String searchtext = (String.valueOf(edittext.getText()));
					if(searchtext.length()>2)
					{
						Intent i = new Intent(Main.this, Main.class);
						i.putExtra(CITY_KEY, city_id);  
						i.putExtra(SEARCH_KEYWORD, searchtext); 
						i.setAction(ACTION_SEARCH_PHARMACIES);          
						startActivity(i);   
					}
					else
						Toast.makeText(getApplicationContext(), getString(R.string.arama_uyari), Toast.LENGTH_SHORT).show();
				}        
			});




			edittext.setOnKeyListener(new OnKeyListener() {
				public boolean onKey(View v, int keyCode, KeyEvent event) {
					// If the event is a key-down event on the "enter" button
					if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
							(keyCode == KeyEvent.KEYCODE_ENTER)) {
						// Perform action on key press

						String searchtext = (String.valueOf(edittext.getText()));										
						if(searchtext.length()>2)
						{
							Intent i = new Intent(Main.this, Main.class);
							i.putExtra(CITY_KEY, city_id);  
							i.putExtra(SEARCH_KEYWORD, searchtext); 
							i.setAction(ACTION_SEARCH_PHARMACIES);          
							startActivity(i);   
						}
						else
							Toast.makeText(getApplicationContext(), getString(R.string.arama_uyari), Toast.LENGTH_SHORT).show();
					}    					
					return false;
				}
			});
		}
		else 
		ad.show();

	}
	
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		MenuInflater inflater = getMenuInflater();

		inflater.inflate(R.menu.menu, menu);
		return true;

	}

	public boolean onOptionsItemSelected(MenuItem item){
		final Dialog dialog = new Dialog(this);
		switch(item.getItemId()){
		case R.id.hakkinda:
			
			dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.about);
			dialog.show();
			
			Button positiveButton = (Button) dialog.findViewById(R.id.positiveButton);

			positiveButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					dialog.cancel();
				}
			});


			break;
		case R.id.ipucu:
			dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.ipucu);
			dialog.show();
			
			Button positiveButton2 = (Button) dialog.findViewById(R.id.positiveButton);

			positiveButton2.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					dialog.cancel();
				}
			});


			break;

		}
		return super.onOptionsItemSelected(item);
	}

	class PharmacyAdapter extends BaseAdapter {

		private ElementInfo[] pharmacies;

		public PharmacyAdapter(Context context, ElementInfo[] pharmacies) {
			mContext = context;
			this.pharmacies = pharmacies;
		}

		public int getCount() {
			return this.pharmacies.length;
		}

		public Object getItem(int position) {
			return pharmacies[position];
		}

		public long getItemId(int position) {
			return pharmacies[position].id;
		}

		public boolean getItemisPharmacy(int position) {
			return pharmacies[position].isPharmacy;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view;


			view = (View) LayoutInflater.from(mContext).inflate(
					R.layout.list_item, parent, false);
			ImageView mapicon = (ImageView)view.findViewById(R.id.mapicon);
			TextView nameView = (TextView)view.findViewById(R.id.name);
			nameView.setText(pharmacies[position].name);
			TextView phoneView = (TextView)view.findViewById(R.id.phone);
			if(pharmacies[position].lattitude==0 && ((pharmacies[position].URL == null || pharmacies[position].URL.equals("0") == true)))
				mapicon.setVisibility(View.GONE);
			if (pharmacies[position].phoneNumber == null || pharmacies[position].phoneNumber.equals("") == true) {
				phoneView.setVisibility(View.GONE);
				mapicon.setVisibility(View.GONE);
				nameView.setPadding(3, 10, 3, 10);
			}
			else {
				phoneView.setText(pharmacies[position].phoneNumber);
				//	Linkify.addLinks(phoneView, Linkify.PHONE_NUMBERS);
			}
			TextView addressView = (TextView)view.findViewById(R.id.address);
			if (pharmacies[position].address == null || pharmacies[position].address.equals("") == true) {
				addressView.setVisibility(View.GONE);
			}
			else {
				addressView.setText(pharmacies[position].address);
			}
			//view.setSingleLine(false);  


			return view;
		}

		private Context mContext;
	}

	
}

